const Base = require('./base.js');


module.exports = class extends Base {
  async indexAction(){
    return this.display();
  };

  async getMenuDataAction(){
    let param = this.post();
    let menuList = [];
    let allMenuData = await this.model("sys_menu").where({del_flag:"0"}).select();
    for(var i = 0; i < allMenuData.length; i++){
      menuList[i] = {};
      menuList[i].title = allMenuData[i].title;
      menuList[i].checked = false;
      if(menuList[i].title == '用户管理' || menuList[i].title == '菜单管理'){
        menuList[i].disabled = true;
      }else{
        menuList[i].disabled = false;
      }
    }
    // let userId = await this.model("sys_user").field("id").where({'username':param.username}).find();
    // think.logger.info(userId);
    let menuId = await this.model("sys_role_menu").where({'role_id': param.id}).select();
    for(var i = 0; i < menuId.length; i ++){
      menuList[menuId[i].menu_id - 1].checked = true;
    }
    return this.success(menuList);
  }

  async updateUserMenuAction(){
    let param = this.post();
    let deleteRows = await this.model("sys_role_menu").where({'role_id':param.role_id}).delete();
    let menuData = param.menuData;
    think.logger.info(menuData);
    for(var i = 0; i < menuData.length; i++){
      await this.model("sys_role_menu").where({'role_id':param.role_id,'menu_id':(menuData[i].nodeKey)+1}).thenAdd({'role_id':param.role_id,'menu_id':(menuData[i].nodeKey)+1});
    }
    let afterEditMenu = await this.model("sys_role_menu").where({'role_id':param.role_id}).select();
    return this.success(afterEditMenu);
  };

  async addMenuAction(){
    let params = this.post();
    console.log(params);
    let menuCount = await this.model('sys_menu').count();
    console.log(menuCount);
    let addParams = {
      'pid':'0',
      'name':params.name,
      'sort':menuCount + 1,
      'href':'singlepage/'+params.href,
      'icon':params.icon,
      'is_show':'1',
      'title':params.title
    };
    let insertID = await this.model('sys_menu').add(addParams);
    return this.success(insertID);
  }

  async updateMenuAction(){
    let params = this.post();
    console.log(params);
    let menuCount = await this.model('sys_menu').count();
    console.log(menuCount);
    let addParams = {
      'pid':'0',
      'name':params.name,
      'sort':menuCount + 1,
      'href':params.href,
      'icon':params.icon,
      'is_show':'1',
      'title':params.title
    };
    let insertID = await this.model('sys_menu').where({id: params.id}).update(addParams);
    return this.success(insertID);
  }

  async deleteMenu(){
    let params = this.post();
    let affRows = await this.model("sys_menu").where({id: params.id}).update({del_flag:1});
    if(affRows > 0){
        return this.success("删除成功");
    }
  }

  async GetMenuListAction(){
    let allMenuData = await this.model("sys_menu").select();
    return this.success(allMenuData);
  }
}